//
//  SpellSubviewController.m
//  Quest CoreData
//
//  Created by Matthew Hutton on 11/02/2007.
//  Copyright 2007 Matthew Hutton. All rights reserved.
//
#import "SpellSubviewController.h"


@implementation SpellSubviewController
//-(id)initFromAppController:(AppController *)theAppController{
-(id)initWithCharController:(NSArrayController *)cCont
		withSpellController:(NSArrayController *)sCont
			withCharTabView:(NSTabView *)tabView{
	[super init];
	//NSLog(@"spell subviews created");
	[NSBundle loadNibNamed:@"SpellSubviews"
					 owner:self];
	charController=cCont;
	spellController=sCont;
	characterTabView=tabView;
	return self;
}
-(NSManagedObjectContext *)managedObjectContext{
	return [[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
}
-(void)reloadSpellTables{
	[currentCharactersSpellsTable reloadData];
	[availableSpellsTable reloadData];
	[spellsOfLevelTable reloadData];
	[spellsPerDayTable reloadData];
	[memorisedSpellTable reloadData];
	[domainSpellsOfLevelTable reloadData];
	//doing domain spells for the current spell level.
	//NSLog(@"1");
	if([[charController selectedObjects] count]==0){
		//NSLog(@"no character selected");
		return;
	}
	int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
	int level2=level;
	NSString *theClass=[memorisedSpellsClass stringValue];
	if([theClass isEqualToString:@"Ranger"] || [theClass isEqualToString:@"Paladin"]){
		level2--;
	}
	//NSLog(@"2");
	NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
	//NSLog(@"3");
	//NSLog(@"obj.name=%@",[obj valueForKey:@"name"]);
	NSArray *array0=[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass matches \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]];
	if([array0 count]==0){
		//NSLog(@"error, %@ doesn't have any relevent spellLevels.",[obj valueForKey:@"name"]);
		return;
	}
	NSManagedObject *spellLevel=[array0 objectAtIndex:level2];
	//NSLog(@"4");
	NSArray *array=[[[spellLevel valueForKey:@"memorisedSpell"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"domain==1"]];
	//NSLog(@"5");
	if([array count]>0){
		[domainMemorisedTextField setStringValue:[[array objectAtIndex:0] valueForKey:@"name"]];
	}else{
		[domainMemorisedTextField setStringValue:@""];
	}
	//NSLog(@"6");
	//check labelling.
	[tooManySpells setHidden:YES];
	[tooFewSpells setHidden:YES];
	if([self numberOfRowsInTableView:memorisedSpellTable]<[[spellLevel valueForKey:@"totalSpells"] intValue]){
		[tooFewSpells setHidden:NO];
	}else if([self numberOfRowsInTableView:memorisedSpellTable]>[[spellLevel valueForKey:@"totalSpells"] intValue]){
		[tooManySpells setHidden:NO];
	}
	//disable/enable buttons as required.
	if([self numberOfRowsInTableView:availableSpellsTable]==0){
		[addToSpellbookButton setEnabled:NO];
	}else{
		[addToSpellbookButton setEnabled:YES];
	}
	if([self numberOfRowsInTableView:currentCharactersSpellsTable]==0){
		[removeFromSpellbookButton setEnabled:NO];
	}else{
		[removeFromSpellbookButton setEnabled:YES];
	}
	if([self numberOfRowsInTableView:spellsOfLevelTable]==0){
		[addToMemorisedSpellsButton setEnabled:NO];
	}else{
		[addToMemorisedSpellsButton setEnabled:YES];
	}
	if([self numberOfRowsInTableView:memorisedSpellTable]==0){
		[removeFromMemorisedSpellsButton setEnabled:NO];
	}else{
		[removeFromMemorisedSpellsButton setEnabled:YES];
	}
	//NSLog(@"f7");
}
-(IBAction)setUpSpellsPerDay:(id)sender{
	if([[charController selectedObjects] count]==0){
		return;
	}
	NSString *theClass=[memorisedSpellsClass stringValue];
	NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
	NSArray *array=[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass MATCHES \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]];
	if([array count]<=[spellsPerDayTable selectedRow]){
		//NSLog(@"not enough spellLevels available");
		return;
	}
	NSManagedObject *spellLevel=[array objectAtIndex:[spellsPerDayTable selectedRow]];
	int ts=[spellsBase intValue]+[spellAbilityBonus intValue]+[spellsMiscBonus intValue];
	int spellCast=[spellsCast intValue];
	[spellTotal setIntValue:ts];
	[spellTotal2 setIntValue:ts];
	[spellsLeft setIntValue:(ts-spellCast)];
	//set values up.
	[spellLevel setValue:[NSNumber numberWithInt:[spellAbilityBonus intValue]]
				  forKey:@"abilityBonusSpells"];
	[spellLevel setValue:[NSNumber numberWithInt:[spellTotal intValue]]
				  forKey:@"totalSpells"];
	[spellLevel setValue:[NSNumber numberWithInt:[spellsLeft intValue]]
				  forKey:@"spellsLeft"];
	[spellLevel setValue:[NSNumber numberWithInt:spellCast]
				  forKey:@"spellsCast"];
	[spellLevel setValue:[NSNumber numberWithInt:[spellsBase intValue]]
				  forKey:@"baseSpells"];
	[spellLevel setValue:[NSNumber numberWithInt:[spellsMiscBonus intValue]]
				  forKey:@"miscBonusSpells"];
	[spellLevel setValue:[NSNumber numberWithInt:[totalAvailableSpells intValue]]
				  forKey:@"totalAvailableSpells"];
	[self reloadSpellTables];
}
-(IBAction)spellToSpellbook:(id)sender{
	if([[charController selectedObjects] count]==0){
		return;
	}
	NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
	//recover spell from table.
	NSString *theClass=[memorisedSpellsClass stringValue];
	if([theClass isEqualToString:@"Sourcerer"]){
		theClass=@"Wizard";
	}
	[spellController setFilterPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1",[theClass lowercaseString]]]];
	NSArray *sort=[spellController sortDescriptors];
	[spellController setSortDescriptors:[NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"level%@",theClass]
																							  ascending:YES],[[NSSortDescriptor alloc] initWithKey:@"name"
																									ascending:YES],nil]];
	if([[spellController arrangedObjects] count]<=[availableSpellsTable selectedRow]){
		return;
	}
	NSManagedObject *spell=[[spellController arrangedObjects] objectAtIndex:[availableSpellsTable selectedRow]];
	NSMutableSet *set=[obj valueForKey:@"spells"];
	//check out the class.
	if([theClass isEqualToString:@"Sourcerer"] || [theClass isEqualToString:@"Bard"]){
		//check whether spell limit is reached.
	}
	[set addObject:spell];
	[obj setValue:set
		   forKey:@"spells"];
	[spellController setSortDescriptors:sort];
	[spellController setFilterPredicate:nil];
	[currentCharactersSpellsTable reloadData];
	//setup spellbook buttons.
	[addToSpellbookButton setEnabled:NO];
	if([self numberOfRowsInTableView:currentCharactersSpellsTable]==0){
		[removeFromSpellbookButton setEnabled:NO];
	}else{
		[removeFromSpellbookButton setEnabled:YES];
	}
}

-(IBAction)spellFromSpellbook:(id)sender{
	if([[charController selectedObjects] count]==0){
		return;
	}
	NSString *theClass=[memorisedSpellsClass stringValue];
	if([theClass isEqualToString:@"Sourcerer"]){
		theClass=@"Wizard";
	}
	NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
	//NSLog(@"before bad on l108 ssc");
	NSManagedObject *spell=[[[[[obj valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1",[theClass lowercaseString]]]] sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"level%@",theClass] ascending:YES],[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES],nil]] objectAtIndex:[currentCharactersSpellsTable selectedRow]];
	//NSLog(@"done");
	NSMutableSet *set=[obj valueForKey:@"spells"];
	[set removeObject:spell];
	[obj setValue:set
		   forKey:@"spells"];
	[currentCharactersSpellsTable reloadData];
	if([self numberOfRowsInTableView:currentCharactersSpellsTable]==0){
		[removeFromSpellbookButton setEnabled:NO];
	}else{
		[removeFromSpellbookButton setEnabled:YES];
	}
	//check if spell that has been removed is the one selected in the current available spells table.
	NSArray *sort=[spellController sortDescriptors];
	[spellController setSortDescriptors:[NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"level%@",theClass] ascending:YES],[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES],nil]];
	if([[spellController arrangedObjects] count]<=[availableSpellsTable selectedRow]){
		return;
	}
	NSManagedObject *spell2=[[spellController arrangedObjects] objectAtIndex:[availableSpellsTable selectedRow]];
	[spellController setSortDescriptors:sort];
	if([spell isEqualTo:spell2]){
		[addToSpellbookButton setEnabled:YES];
	}
}
-(IBAction)spellToMemorised:(id)sender{
	NSString *theClass=[memorisedSpellsClass stringValue];
	if([theClass isEqualToString:@"Sourcerer"]){
		theClass=@"Wizard";
	}
	if([[charController selectedObjects] count]==0)
		return;
	int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
	int level2=level;
	if([theClass isEqualToString:@"Ranger"] || [theClass isEqualToString:@"Paladin"]){
		level2--;
	}
	//check metamagic whether enabled.
	if([metaMagicFeats isEnabled] && [metaMagicFeats state]==NSOnState){
		//NSLog(@"before bad ssc l132");
		NSManagedObject *spellLevel2=[[[[[[[charController selectedObjects] objectAtIndex:0] valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass matches \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]] objectAtIndex:(level2+1)];
		//NSLog(@"done");
		if([[spellLevel2 valueForKey:@"totalSpells"] intValue]>0){
			//NSLog(@"1");
			[metaMagicTable reloadData];
						//NSLog(@"2");
			[metaMagicWarning setHidden:YES];
						//NSLog(@"3");
			NSWindow *mw=[characterTabView window];
			//NSLog(@"3.5");
			[NSApp beginSheet:metaMagicSheet
			   modalForWindow:mw
				modalDelegate:self
			   didEndSelector:nil
				  contextInfo:NULL];
			return;
			//NSLog(@"4");
		}
	}
	//NSLog(@"before bad ssc l152");
	NSManagedObject *spellLevel=[[[[[[[charController selectedObjects] objectAtIndex:0] valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass matches \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]] objectAtIndex:level2];
	//NSLog(@"done, before bad ssc l155");
	//NSLog(@"spellLevel=%@",spellLevel);
	NSManagedObject *spell=[[[[[[[charController selectedObjects] objectAtIndex:0] valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1 AND level%@==%d",[theClass lowercaseString],theClass,level]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]] objectAtIndex:[spellsOfLevelTable selectedRow]];
	//NSLog(@"done");
	//NSLog(@"spell name=%@",[spell valueForKey:@"name"]);
	NSManagedObjectContext *mObjC=[[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
	NSManagedObjectModel *model=[[mObjC persistentStoreCoordinator] managedObjectModel];
	NSManagedObject *mSpell=[[NSManagedObject alloc] initWithEntity:[[model entitiesByName]  objectForKey:@"MemorisedSpell"]
									 insertIntoManagedObjectContext:mObjC];
	[mSpell setValue:[spell valueForKey:@"name"]
			  forKey:@"name"];
	[mSpell setValue:spell
			  forKey:@"spell"];
	[mSpell setValue:spellLevel
			  forKey:@"spellLevel"];
	[memorisedSpellTable reloadData];
	//check labelling.
	[tooManySpells setHidden:YES];
	[tooFewSpells setHidden:YES];
	if([self numberOfRowsInTableView:memorisedSpellTable]<[[spellLevel valueForKey:@"totalSpells"] intValue]){
		[tooFewSpells setHidden:NO];
	}else if([self numberOfRowsInTableView:memorisedSpellTable]>[[spellLevel valueForKey:@"totalSpells"] intValue]){
		[tooManySpells setHidden:NO];
	}
	if([self numberOfRowsInTableView:memorisedSpellTable]==0){
		[removeFromMemorisedSpellsButton setEnabled:NO];
	}else{
		[removeFromMemorisedSpellsButton setEnabled:YES];
	}
}
-(IBAction)spellFromMemorised:(id)sender{
	if([[charController selectedObjects] count]==0)
		return;
	int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
	int level2=level;
	NSString *theClass=[memorisedSpellsClass stringValue];
	if([theClass isEqualToString:@"Ranger"] || [theClass isEqualToString:@"Paladin"]){
		level2--;
	}
	NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
	//NSLog(@"before bad l189 ssc");
	NSManagedObject *spellLevel=[[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass matches \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]] objectAtIndex:level2];
	NSManagedObject *memSpell=[[[[[spellLevel valueForKey:@"memorisedSpell"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"domain==0"]] sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:@"castable" ascending:NO],[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES],nil]] objectAtIndex:[memorisedSpellTable selectedRow]];
	//NSLog(@"done");
	NSManagedObjectContext *mObjC=[[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
	[memSpell setValue:nil
				forKey:@"spellLevel"];
	[mObjC deleteObject:memSpell];
	[memorisedSpellTable reloadData];
	//check labelling.
	[tooManySpells setHidden:YES];
	[tooFewSpells setHidden:YES];
	if([self numberOfRowsInTableView:memorisedSpellTable]<[[spellLevel valueForKey:@"totalSpells"] intValue]){
		[tooFewSpells setHidden:NO];
	}else if([self numberOfRowsInTableView:memorisedSpellTable]>[[spellLevel valueForKey:@"totalSpells"] intValue]){
		[tooManySpells setHidden:NO];
	}
	if([self numberOfRowsInTableView:memorisedSpellTable]==0){
		[removeFromMemorisedSpellsButton setEnabled:NO];
	}else{
		[removeFromMemorisedSpellsButton setEnabled:YES];
	}
}
-(IBAction)spellToDomain:(id)sender{
	//check if existing spell
	if(![[domainMemorisedTextField stringValue] isEqualToString:@""]){
		[self spellFromDomain];
	}
	NSString *theClass=[memorisedSpellsClass stringValue];
	if([theClass isEqualToString:@"Sourcerer"]){
		theClass=@"Wizard";
	}
	if([[charController selectedObjects] count]==0)
		return;
	int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
	int level2=level;
	if([theClass isEqualToString:@"Ranger"] || [theClass isEqualToString:@"Paladin"]){
		level2--;
	}
	NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
	//NSLog(@"bad bit l223, ssc");
	NSManagedObject *spellLevel=[[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass matches \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]] objectAtIndex:level2];
	//NSLog(@"spellLevel=%@",spellLevel);
	NSManagedObject *spell=[[[[[obj valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"domain==1 AND (domainName like[c] \"%@\" OR domainName like[c] \"%@\") AND levelDomain==%d",[obj valueForKey:@"domain1"],[obj valueForKey:@"domain2"],level]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]] objectAtIndex:[domainSpellsOfLevelTable selectedRow]];
	//NSLog(@"done");
	//NSLog(@"spell name=%@",[spell valueForKey:@"name"]);
	NSManagedObjectContext *mObjC=[[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
	NSManagedObjectModel *model=[[mObjC persistentStoreCoordinator] managedObjectModel];
	NSManagedObject *mSpell=[[NSManagedObject alloc] initWithEntity:[[model entitiesByName]  objectForKey:@"MemorisedSpell"]
									 insertIntoManagedObjectContext:mObjC];
	[mSpell setValue:[spell valueForKey:@"name"]
			  forKey:@"name"];
	[mSpell setValue:spell
			  forKey:@"spell"];
	[mSpell setValue:spellLevel
			  forKey:@"spellLevel"];
	[mSpell setValue:[NSNumber numberWithBool:YES]
			  forKey:@"domain"];
	[domainMemorisedTextField setStringValue:[mSpell valueForKey:@"name"]];
}
-(IBAction)spellFromDomain:(id)sender{
	[self spellFromDomain];
}
-(void)spellFromDomain{
	if([[charController selectedObjects] count]==0)
		return;
	int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
	int level2=level;
	NSString *theClass=[memorisedSpellsClass stringValue];
	if([theClass isEqualToString:@"Ranger"] || [theClass isEqualToString:@"Paladin"]){
		level2--;
	}
	NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
	//NSLog(@"before bad l256 ssc");
	NSManagedObject *spellLevel=[[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass matches \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]] objectAtIndex:level2];
	NSManagedObject *memSpell=[[[[spellLevel valueForKey:@"memorisedSpell"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"domain==1"]] objectAtIndex:0];
	//NSLog(@"done");
	NSManagedObjectContext *mObjC=[[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
	[memSpell setValue:nil
				forKey:@"spellLevel"];
	[mObjC deleteObject:memSpell];
	[domainMemorisedTextField setStringValue:@""];
}
-(IBAction)metaMagicSheetEnded:(id)sender{
	[metaMagicSheet orderOut:sender];
	[NSApp endSheet:metaMagicSheet];
	if([[charController selectedObjects] count]==0)
		return;
	NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
	NSIndexSet *is=[metaMagicTable selectedRowIndexes];
	NSSet *set=[NSSet setWithArray:[[[[obj valueForKey:@"feats"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"type==2 AND active==1"]] objectsAtIndexes:is]];
	//got the feats.
	int levelPlus=0;
	int i;
	NSArray *arrayOfFeats=[set allObjects];
	for(i=0;i<[arrayOfFeats count];i++){
		NSManagedObject *feat=[arrayOfFeats objectAtIndex:i];
		//get any x values.
		/*NSString *str=[self tableView:metaMagicTable objectValueForTableColumn:[[metaMagicTable tableColumns] objectAtIndex:1] row:i];
		if([[feat valueForKey:@"spellMod"] hasSuffix:@"x"]){
			[feat setValue:[NSNumber numberWithInt:[str intValue]]
					forKey:@"xValue"];
		}*/
		//level plus.
		levelPlus=levelPlus+[[feat valueForKey:@"spellLevelMod"] intValue];
	}
	//set up memorised spell.
	NSString *theClass=[memorisedSpellsClass stringValue];
	if([theClass isEqualToString:@"Sourcerer"]){
		theClass=@"Wizard";
	}
	if([[charController selectedObjects] count]==0)
		return;
	int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
	int level2=level;
	if([theClass isEqualToString:@"Ranger"] || [theClass isEqualToString:@"Paladin"]){
		level2--;
	}
	//NSLog(@"bad @ l286 ssc");
	NSManagedObject *spellLevel=[[[[[[[charController selectedObjects] objectAtIndex:0] valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass matches \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]] objectAtIndex:(level2+levelPlus)];
	NSManagedObject *spell=[[[[[[charController selectedObjects] objectAtIndex:0] valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1 AND level%@==%d",[theClass lowercaseString],theClass,level]]] objectAtIndex:[spellsOfLevelTable selectedRow]];
	//NSLog(@"done");
	NSManagedObjectContext *mObjC=[[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
	NSManagedObjectModel *model=[[mObjC persistentStoreCoordinator] managedObjectModel];
	NSManagedObject *mSpell=[[NSManagedObject alloc] initWithEntity:[[model entitiesByName]  objectForKey:@"MemorisedSpell"]
									 insertIntoManagedObjectContext:mObjC];
	[mSpell setValue:[NSString stringWithFormat:@"%@*",[spell valueForKey:@"name"]]
			  forKey:@"name"];
	[mSpell setValue:spell
			  forKey:@"spell"];
	[mSpell setValue:spellLevel
			  forKey:@"spellLevel"];
	[mSpell setValue:set
			  forKey:@"feat"];
	if([is count]==0){
		[mSpell setValue:[spell valueForKey:@"name"]
				  forKey:@"name"];
		[memorisedSpellTable reloadData];
	}else{
		[mSpell setValue:[NSString stringWithFormat:@"%@*",[spell valueForKey:@"name"]]
				  forKey:@"name"];
		[memorisedSpellsTabs selectTabViewItemAtIndex:(level2+levelPlus)];
	}
	//check labelling.
	[tooManySpells setHidden:YES];
	[tooFewSpells setHidden:YES];
	if([self numberOfRowsInTableView:memorisedSpellTable]<[[spellLevel valueForKey:@"totalSpells"] intValue]){
		[tooFewSpells setHidden:NO];
	}else if([self numberOfRowsInTableView:memorisedSpellTable]>[[spellLevel valueForKey:@"totalSpells"] intValue]){
		[tooManySpells setHidden:NO];
	}
}
-(IBAction)domain1Setup:(id)sender{
	if([[charController selectedObjects] count]==0){
		return;
	}
	[[[charController selectedObjects] objectAtIndex:0] setValue:[domainCombo1 stringValue]
														  forKey:@"domain1"];
}
-(IBAction)domain2Setup:(id)sender{
	if([[charController selectedObjects] count]==0){
		return;
	}
	[[[charController selectedObjects] objectAtIndex:0] setValue:[domainCombo2 stringValue]
														  forKey:@"domain2"];
}
-(void)magicViewOpenedForChar:(NSManagedObject *)obj{
	if(magicViewChanging==YES)
		return;
	magicViewChanging=YES;
	/*if (ssController == nil){
	ssController = [[SpellSubviewController alloc] initWithWindowNibName:@"SecondWindow"]; 
	}
	*/
	//NSLog(@"magic view started");
	//check how many magic casting classes the character has.
	int count=0;
	BOOL c1=NO,c2=NO,c3=NO;
	if([self classAMagicCaster:[obj valueForKey:@"charClassName1"]]){
		c1=YES;
		count++;
	}
	if([self classAMagicCaster:[obj valueForKey:@"charClassName2"]]){
		c2=YES;
		count++;
	}
	if([self classAMagicCaster:[obj valueForKey:@"charClassName3"]]){
		c3=YES;
		count++;
	}
	NSTabViewItem *magicView=[characterTabView tabViewItemAtIndex:3];
	//NSLog(@"choosing options");
	//NSLog(@"noSpellsView=%@",noSpellsView);
	if(count==0){
		[magicView setView:noSpellsView];
	}else if(count==1){
		NSString *theClass;
		if(c1){
			theClass=[obj valueForKey:@"charClassName1"];
		}else if(c2){
			theClass=[obj valueForKey:@"charClassName2"];
		}else{
			theClass=[obj valueForKey:@"charClassName3"];
		}
		[self processMagicView:magicView
					  forClass:theClass
					   forChar:obj];
	}else if(count==2){
		[magicView setView:twoSpellClassesView];
		//set the labels of the tabs.
		NSArray *array=[twoSpellClassesTab tabViewItems];
		if([array count]<2){
			//NSLog(@"not enough objects");
			return;
		}
		if(c1){
			[[array objectAtIndex:0] setLabel:[obj valueForKey:@"charClassName1"]];
			if(c2){
				[[array objectAtIndex:1] setLabel:[obj valueForKey:@"charClassName2"]];
			}else{
				[[array objectAtIndex:1] setLabel:[obj valueForKey:@"charClassName3"]];
			}
		}else{
			[[array objectAtIndex:0] setLabel:[obj valueForKey:@"charClassName2"]];
			[[array objectAtIndex:1] setLabel:[obj valueForKey:@"charClassName3"]];
		}
		//now check which view is visible and deal.
		int currentTab=[twoSpellClassesTab indexOfTabViewItem:[twoSpellClassesTab selectedTabViewItem]];
		NSString *theClass;
		//NSLog(@"currentTab=%d",currentTab);
		if(currentTab==0){
			if(c1){
				theClass=[obj valueForKey:@"charClassName1"];
			}else{
				theClass=[obj valueForKey:@"charClassName2"];
			}
			[self processMagicView:[array objectAtIndex:0]
						  forClass:theClass
						   forChar:obj];
		}else{
			if(c2){
				theClass=[obj valueForKey:@"charClassName2"];
			}else{
				theClass=[obj valueForKey:@"charClassName3"];
			}
			[self processMagicView:[array objectAtIndex:1]
						  forClass:theClass
						   forChar:obj];
			
		}
	}else{
		[magicView setView:threeSpellClassesView];
		//set the labels of the tabs.
		NSArray *array=[threeSpellClassesTab tabViewItems];
		if([array count]<3){
			return;
		}
		[[array objectAtIndex:0] setLabel:[obj valueForKey:@"charClassName1"]];
		[[array objectAtIndex:1] setLabel:[obj valueForKey:@"charClassName2"]];
		[[array objectAtIndex:2] setLabel:[obj valueForKey:@"charClassName3"]];
		//now check which view is visible and deal.
		int currentTab=[threeSpellClassesTab indexOfTabViewItem:[threeSpellClassesTab selectedTabViewItem]];
		//NSLog(@"currentTab=%d",currentTab);
		NSString *theClass;
		theClass=[obj valueForKey:[NSString stringWithFormat:@"charClassName%d",(currentTab+1)]];
		//[[array objectAtIndex:currentTab] setView:nil];
		/*NSTabViewItem *oldView=[array objectAtIndex:currentTab];
		NSTabViewItem *newView=[[NSTabViewItem alloc] init];
		[newView setLabel:[oldView label]];
		[threeSpellClassesTab insertTabViewItem:newView atIndex:[threeSpellClassesTab indexOfTabViewItem:oldView]];
		[newView setView:spellsAvailableView];
		[threeSpellClassesTab removeTabViewItem:oldView];*/
		if(currentTab>=[array count]){
			return;
		}
		[self processMagicView:[array objectAtIndex:currentTab]
					  forClass:theClass
					   forChar:obj];
	}
	magicViewChanging=NO;
	//NSLog(@"magic view ended");
}
-(void)processMagicView:(NSTabViewItem *)magicView
			   forClass:(NSString *)theClass
				forChar:(NSManagedObject *)obj{
	/*NSTabViewItem *oldView=magicView;
	NSTabViewItem *newView=[[NSTabViewItem alloc] init];
	[newView setLabel:[oldView label]];
	[[oldView tabView] insertTabViewItem:newView atIndex:[[oldView tabView] indexOfTabViewItem:oldView]];
	[newView setView:spellsAvailableView];
	magicView=newView;
	[[magicView tabView] removeTabViewItem:oldView];*/
	[magicView setView:spellsAvailableView];
	//NSLog(@"1");
	[self createSpellLevels:theClass
					forChar:obj];
	//NSLog(@"1.5");
	[domainSpells setHidden:YES];
	[noOfDomainSpells setHidden:YES];
	[spellsPerDayBox setHidden:YES];
	NSRect rect=[spellsPerDayBox frame];
	rect.size.width=236;
	[domainSpellsOfLevelScroll setHidden:YES];
	[domainSpellsOfLevelBox setHidden:YES];
	[addToDomainSpellsButton setHidden:YES];
	[domainSpellOptionsView setHidden:YES];
	[removeFromDomainSpellsButton setHidden:YES];
	[totalSpellOptionsView setHidden:YES];
	[spellsPerDayBox setFrame:rect];
	[spellsPerDayBox setHidden:NO];
	[memorisedSpellsClass setStringValue:theClass];
	//NSLog(@"2");
	if([theClass isEqualToString:@"Cleric"]){
		[domainSpells setHidden:NO];
		[noOfDomainSpells setHidden:NO];
		NSRect rect=[spellsPerDayBox frame];
		rect.size.width=288;
		[spellsPerDayBox setFrame:rect];
		//show domain related stuff...
		[domainSpellOptionsView setHidden:NO];
		[domainSpellsOfLevelScroll setHidden:NO];
		[domainSpellsOfLevelBox setHidden:NO];
		[addToDomainSpellsButton setHidden:NO];
		[removeFromDomainSpellsButton setHidden:NO];
		//now get domain values.
		[domainCombo1 setStringValue:[obj valueForKey:@"domain1"]];
		[domainCombo2 setStringValue:[obj valueForKey:@"domain2"]];
		if(![[[spellOptionsTabs tabViewItemAtIndex:1] label] isEqualToString:@"Memorised Spells"]){
			NSTabViewItem *tabViewItem=[[[NSTabViewItem alloc] init] autorelease];
			[tabViewItem setLabel:@"Memorised Spells"];
			[tabViewItem setView:memorisedSpellsTotalView];
			[spellOptionsTabs insertTabViewItem:tabViewItem
										atIndex:1];
		}
		[self setUpMemorised:memorisedSpellsTabs
					 forChar:obj
					forClass:theClass];
	}else if([theClass isEqualToString:@"Sourcerer"] || [theClass isEqualToString:@"Bard"]){
		//NSLog(@"s/b opt");
		[totalSpellOptionsView setHidden:NO];
		if([[[spellOptionsTabs tabViewItemAtIndex:1] label] isEqualToString:@"Memorised Spells"]){
			[spellOptionsTabs removeTabViewItem:[spellOptionsTabs tabViewItemAtIndex:1]];	
		}
		//NSLog(@"s/b opt done");
	}else{
		if(![[[spellOptionsTabs tabViewItemAtIndex:1] label] isEqualToString:@"Memorised Spells"]){
			NSTabViewItem *tabViewItem=[[[NSTabViewItem alloc] init] autorelease];
			[tabViewItem setLabel:@"Memorised Spells"];
			[tabViewItem setView:memorisedSpellsTotalView];
			[spellOptionsTabs insertTabViewItem:tabViewItem
										atIndex:1];
		}
		[self setUpMemorised:memorisedSpellsTabs
					 forChar:obj
					forClass:theClass];
	}
	//NSLog(@"3");
	[self reloadSpellTables];
	//NSLog(@"4");
	//[spellController setFilterPredicate:nil];
	////NSLog(@"spellsAvailable=%@, magicView.view=%@",spellsAvailable,[magicView view]);
	//NSLog(@"5");
}
-(void)setUpMemorised:(NSTabView *)tabView
			  forChar:(NSManagedObject *)obj
			 forClass:(NSString *)theClass{
	NSTabViewItem *tabViewItem=[tabView selectedTabViewItem];
	int level=[tabView indexOfTabViewItem:tabViewItem];
	//NSLog(@"number of tab view items=%d",[tabView numberOfTabViewItems]);
	//check correct number of tabs visible.
	if([theClass isEqualToString:@"Paladin"] || [theClass isEqualToString:@"Ranger"]){
		//NSLog(@"pal/ranger");
		if([tabView numberOfTabViewItems]==10){
			//NSLog(@"not 4 entries");
			[tabView removeTabViewItem:[tabView tabViewItemAtIndex:0]];
			//NSLog(@"number of tab view items (just removed, no loop)=%d",[tabView numberOfTabViewItems]);
			int i;
			for(i=0;i<5;i++){
				[tabView removeTabViewItem:[tabView tabViewItemAtIndex:4]];
				//NSLog(@"number of tab view items (just removed, loop)=%d",[tabView numberOfTabViewItems]);
			}
		}else{
			level++;
		}
		if(level>4){
			level=4;
		}else if(level==0){
			level=1;
		}
	}else{
		//NSLog(@"other");
		if([tabView numberOfTabViewItems]==4){
			level++;
			//NSLog(@"not 10 entries");
			int i;
			for(i=0;i<6;i++){
				NSTabViewItem *tabViewItem=[[[NSTabViewItem alloc] init] autorelease];
				if(i==0){
					[tabViewItem setLabel:@"0"];
					[tabView insertTabViewItem:tabViewItem
									   atIndex:0];
				}else{
					[tabViewItem setLabel:[NSString stringWithFormat:@"%d",(i+4)]];
					[tabView addTabViewItem:tabViewItem];
				}
			}
		}
	}
	//check metamagic feats.
	if([[[[obj valueForKey:@"feats"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"type==2 AND active==1"]] count]==0){
		[metaMagicFeats setEnabled:NO];
	}else{
		[metaMagicFeats setEnabled:YES];
	}
	//check has right number of tabs.
	if([[spellsOfLevelTable tableColumns] count]==0){
		return;
	}
	NSTableColumn *tc=[[spellsOfLevelTable tableColumns] objectAtIndex:0];
	NSTableHeaderCell *header=[tc headerCell];
	[header setStringValue:[NSString stringWithFormat:@"All Spells of Level %d",level]];
	[tc setHeaderCell:header];
	[spellsOfLevelTable reloadData];//try reloading to see if helps.
	tc=[[domainSpellsOfLevelTable tableColumns] objectAtIndex:0];
	header=[tc headerCell];
	[header setStringValue:[NSString stringWithFormat:@"Domain Spells of Level %d",level]];
	[tc setHeaderCell:header];
	//[domainSpellsOfLevelTable reloadData];//try reloading to see if helps.
	[domainSpellsOfLevelBox setTitle:[NSString stringWithFormat:@"Memorised Domain Spell of Level %d",level]];
	//set up table data and stuff.
	[tabViewItem setView:memorisedSpellView];
	[self reloadSpellTables];
}
-(BOOL)classAMagicCaster:(NSString *)theClass{
	if([theClass isEqualToString:@"Wizard"] || [theClass isEqualToString:@"Sourcerer"] || [theClass isEqualToString:@"Bard"]
	   || [theClass isEqualToString:@"Cleric"] || [theClass isEqualToString:@"Druid"] || [theClass isEqualToString:@"Paladin"] || [theClass isEqualToString:@"Ranger"] ){
		return YES;
	}
	return NO;
}
-(BOOL)createSpellLevels:(NSString *)theClass
				 forChar:(NSManagedObject *)obj{
	//NSLog(@"1");
	//check if spell levels already exsist.
	NSArray *spellLevels=[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"charClass == %@",theClass]];
	//NSLog(@"1.05");
	if([spellLevels count]==0){
		//NSLog(@"spell levels don't exist");
		//NSLog(@"1.1");
		int spellLevel,i;
		if([theClass isEqualToString:@"Bard"]){
			i=0;
			spellLevel=7;
		}else if([theClass isEqualToString:@"Paladin"] || [theClass isEqualToString:@"Ranger"]){
			i=1;
			spellLevel=5;
		}else{
			i=0;
			spellLevel=10;
		}
		for(i;i<spellLevel;i++){
			NSManagedObjectContext *mObjC=[[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
			NSManagedObjectModel *model=[[mObjC persistentStoreCoordinator] managedObjectModel];
			NSManagedObject *sLevel=[[NSManagedObject alloc] initWithEntity:[[model entitiesByName]  objectForKey:@"SpellLevel"]
											 insertIntoManagedObjectContext:mObjC];
			[sLevel setValue:[NSNumber numberWithInt:i]
					  forKey:@"level"];
			[sLevel setValue:theClass
					  forKey:@"charClass"];
			[sLevel setValue:obj
					  forKey:@"character"];
		}
		//NSLog(@"1.2");
	}
	if([spellsPerDayTable selectedRow]==-1){
		//NSLog(@"1.4");
		[spellsPerDayTable selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];
		//NSLog(@"1.5");
		[spellAbilityO setHidden:NO];
		[spellAbilityBonus setHidden:YES];
	}
	//NSLog(@"2");
	return YES;
}
-(void)tableViewSelectionDidChange:(NSNotification *)notification{
	//NSLog(@"spell table selection changed");
	if([[notification object] isEqualTo:spellsPerDayTable]){
		if(!([spellsPerDayTable numberOfSelectedRows]==0)){
			NSString *theClass=[memorisedSpellsClass stringValue];
			int level=[spellsPerDayTable selectedRow];
			if([theClass isEqualToString:@"Ranger"] || [theClass isEqualToString:@"Paladin"]){
				level++;
			}
			//NSLog(@"spells per day table selection to update");
			if([[charController selectedObjects] count]==0){
				return;
			}
			//NSLog(@"spells per day table selection updating");
			NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
			//NSLog(@"bad at l689 ssc");
			NSManagedObject *spellLevel=[[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass MATCHES \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]] objectAtIndex:[spellsPerDayTable selectedRow]];
			//NSLog(@"done");
			[spellAbilityBonus setIntValue:[[spellLevel valueForKey:@"abilityBonusSpells"] intValue]];
			[spellTotal setIntValue:[[spellLevel valueForKey:@"totalSpells"] intValue]];
			[spellTotal2 setIntValue:[[spellLevel valueForKey:@"totalSpells"] intValue]];
			[spellsLeft setIntValue:[[spellLevel valueForKey:@"spellsLeft"] intValue]];
			[spellsCast setIntValue:[[spellLevel valueForKey:@"spellsCast"] intValue]];
			[spellsBase setIntValue:[[spellLevel valueForKey:@"baseSpells"] intValue]];
			[spellsMiscBonus setIntValue:[[spellLevel valueForKey:@"miscBonusSpells"] intValue]];
			[totalAvailableSpells setIntValue:[[spellLevel valueForKey:@"totalAvailableSpells"] intValue]];
			if(level==0){
				[noOfDomainSpells setIntValue:0];
				[spellAbilityO setHidden:NO];
				[spellAbilityBonus setHidden:YES];
			}else{
				[noOfDomainSpells setIntValue:1];
				[spellAbilityO setHidden:YES];
				[spellAbilityBonus setHidden:NO];
			}
		}
	}else if([[notification object] isEqualTo:metaMagicTable]){
		NSString *theClass=[memorisedSpellsClass stringValue];
		int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
		int level2=level;
		if([theClass isEqualToString:@"Ranger"] || [theClass isEqualToString:@"Paladin"]){
			level2--;
		}
		if([[charController selectedObjects] count]==0){
			//NSLog(@"Strangely no character selected, (metaMagicTable)");
			return;
		}
		NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
		NSArray *array=[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass matches \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]];
		//get the feats.
		NSIndexSet *is=[metaMagicTable selectedRowIndexes];
		int levelPlus=0;
		int i;
		NSArray *arrayOfFeats=[[[[obj valueForKey:@"feats"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"type==2 AND active==1"]] objectsAtIndexes:is];
		for(i=0;i<[arrayOfFeats count];i++){
			levelPlus=levelPlus+[[[arrayOfFeats objectAtIndex:i] valueForKey:@"spellLevelMod"] intValue];
		}
		//spell level doesn't exist.
		if((level2+levelPlus)>=[array count]){
			[metaMagicWarning setHidden:NO];
			[metaMagicContinueButton setEnabled:NO];
			NSBeep();
			return;
		}else{
			[metaMagicWarning setHidden:YES];
			[metaMagicContinueButton setEnabled:YES];
		}
		//cannot cast spells at level.
		//NSLog(@"bad @ line 752 ssc");
		NSManagedObject *spellLevel=[array objectAtIndex:(level2+levelPlus)];
		//NSLog(@"done");
		if([[spellLevel valueForKey:@"totalSpells"] intValue]==0){
			[metaMagicWarning setHidden:NO];
			[metaMagicContinueButton setEnabled:NO];
			NSBeep();
		}else{
			[metaMagicWarning setHidden:YES];
			[metaMagicContinueButton setEnabled:YES];
		}
	}else if([[notification object] isEqualTo:spellsOfLevelTable]){
		if([self numberOfRowsInTableView:spellsOfLevelTable]==0){
			[addToMemorisedSpellsButton setEnabled:NO];
		}else{
			[addToMemorisedSpellsButton setEnabled:YES];
		}
	}else if([[notification object] isEqualTo:memorisedSpellTable]){
		if([self numberOfRowsInTableView:memorisedSpellTable]==0){
			[removeFromMemorisedSpellsButton setEnabled:NO];
		}else{
			[removeFromMemorisedSpellsButton setEnabled:YES];
		}
	}else if([[notification object] isEqualTo:availableSpellsTable]){
		if([self numberOfRowsInTableView:availableSpellsTable]==0){
			[addToSpellbookButton setEnabled:NO];
		}else{
			if([[charController selectedObjects] count]==0){
				NSLog(@"no character selected cannot process the selection of the available spells table.");
				return;
			}
			NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
			NSString *theClass=[memorisedSpellsClass stringValue];
			if([theClass isEqualToString:@"Sourcerer"]){
				theClass=@"Wizard";
			}
			//check if selected item in currentCharacters, first get it.
			[spellController setFilterPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1",[theClass lowercaseString]]]];
			NSArray *sort=[spellController sortDescriptors];
			[spellController setSortDescriptors:[NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"level%@",theClass] ascending:YES],[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES],nil]];
			NSManagedObject *availableSpell=[[spellController arrangedObjects] objectAtIndex:[availableSpellsTable selectedRow]];
			[spellController setSortDescriptors:sort];
			[spellController setFilterPredicate:nil];
			//now check if it is in the current characters spell list.
			if([[[[[obj valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1",[theClass lowercaseString]]]] sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"level%@",theClass] ascending:YES],[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES],nil]] containsObject:availableSpell]){
				[addToSpellbookButton setEnabled:NO];
			}else{
				[addToSpellbookButton setEnabled:YES];
			}
		}
	}else if([[notification object] isEqualTo:currentCharactersSpellsTable]){
		if([self numberOfRowsInTableView:currentCharactersSpellsTable]==0){
			[removeFromSpellbookButton setEnabled:NO];
		}else{
			[removeFromSpellbookButton setEnabled:YES];
		}
	}	
}
	
- (void)tabView:(NSTabView *)tabView
didSelectTabViewItem:(NSTabViewItem *)tabViewItem{
	//NSLog(@"spell tabs changed");
	if([tabView isEqualTo:memorisedSpellsTabs]){
		if([[charController selectedObjects] count]!=0){
			[self setUpMemorised:tabView
						 forChar:[[charController selectedObjects] objectAtIndex:0]
						forClass:[memorisedSpellsClass stringValue]];
		}
	}else if([tabView isEqualTo:twoSpellClassesTab]){
		if([[charController selectedObjects] count]!=0){
			[self magicViewOpenedForChar:[[charController selectedObjects] objectAtIndex:0]];
		}
	}else if([tabView isEqualTo:threeSpellClassesTab]){
		if([[charController selectedObjects] count]!=0){
			[self magicViewOpenedForChar:[[charController selectedObjects] objectAtIndex:0]];
		}
	}else if([tabView isEqualTo:spellOptionsTabs]){
		[self reloadSpellTables];
	}
}
-(BOOL)tableView:(NSTableView *)aTableView shouldSelectRow:(int)rowIndex{
	
	return YES;
}
-(int)numberOfRowsInTableView:(NSTableView *)aTableView{
	//NSLog(@"spell table no of rows changed");
	if([aTableView isEqualTo:availableSpellsTable]){
		NSString *theClass=[memorisedSpellsClass stringValue];
		if([theClass isEqualToString:@"Sourcerer"]){
			theClass=@"Wizard";
		}
		[spellController setFilterPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1",[theClass lowercaseString]]]];
		return [[spellController arrangedObjects] count];
		[spellController setFilterPredicate:nil];
	}else if([aTableView isEqualTo:currentCharactersSpellsTable]){
		NSString *theClass=[memorisedSpellsClass stringValue];
		if([theClass isEqualToString:@"Sourcerer"]){
			theClass=@"Wizard";
		}
		if([[charController selectedObjects] count]==0)
			return 0;
		return [[[[[[charController selectedObjects] objectAtIndex:0] valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1",[theClass lowercaseString]]]] count];
	}else if([aTableView isEqualTo:spellsOfLevelTable]){
		NSString *theClass=[memorisedSpellsClass stringValue];
		if([theClass isEqualToString:@"Sourcerer"]){
			theClass=@"Wizard";
		}
		if([[charController selectedObjects] count]==0)
			return 0;
		int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
		return [[[[[[charController selectedObjects] objectAtIndex:0] valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1 AND level%@==%d",[theClass lowercaseString],theClass,level]]] count];
	}else if([aTableView isEqualTo:domainSpellsOfLevelTable]){
		if([[charController selectedObjects] count]==0)
			return 0;
		int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
		NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
		return [[[[obj valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"domain==1 AND (domainName like[c] \"%@\" OR domainName like[c] \"%@\") AND levelDomain==%d",[obj valueForKey:@"domain1"],[obj valueForKey:@"domain2"],level]]] count];
	}else if([aTableView isEqualTo:spellsPerDayTable]){
		NSString *theClass=[memorisedSpellsClass stringValue];
		if([[charController selectedObjects] count]==0)
			return 0;
		return [[[[[[charController selectedObjects] objectAtIndex:0] valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass MATCHES \"%@\"",theClass]]] count];
	}else if([aTableView isEqualTo:memorisedSpellTable]){
		if([[charController selectedObjects] count]==0)
			return 0;
		int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
		int level2=level;
		NSString *theClass=[memorisedSpellsClass stringValue];
		if([theClass isEqualToString:@"Ranger"] || [theClass isEqualToString:@"Paladin"]){
			level2--;
		}
		if([[charController selectedObjects] count]==0)
			return 0;
		NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
		//NSLog(@"bad @ line 825 ssc");
		NSArray *array=[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass matches \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]];
		if([array count]<=level2){//error here if array count is 0 hits every startup.
			return 0;
		}
		NSManagedObject *spellLevel=[array objectAtIndex:level2];
		//NSLog(@"done");
		//NSLog(@"count of values=%d",[[[spellLevel valueForKey:@"memorisedSpell"] allObjects] count]);
		int count=[[[[spellLevel valueForKey:@"memorisedSpell"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"domain==0"]] count];
		return count;
	}else if([aTableView isEqualTo:metaMagicTable]){
		if([[charController selectedObjects] count]==0)
			return 0;
		NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
		return [[[[obj valueForKey:@"feats"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"type==2 AND active==1"]] count];
	}
	return 0;
}
-(id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
		   row:(int)row{
	//NSLog(@"spell table data changed");
	if([aTableView isEqualTo:availableSpellsTable]){
		NSString *theClass=[memorisedSpellsClass stringValue];
		if([theClass isEqualToString:@"Sourcerer"]){
			theClass=@"Wizard";
		}
		[spellController setFilterPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1",[theClass lowercaseString]]]];
		NSArray *sort=[spellController sortDescriptors];
		[spellController setSortDescriptors:[NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"level%@",theClass] ascending:YES],[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES],nil]];
		if([aTableColumn isEqualTo:[[aTableView tableColumns] objectAtIndex:0]]){
			return [[[spellController arrangedObjects] objectAtIndex:row] valueForKey:[NSString stringWithFormat:@"level%@",theClass]];
		}else{
			return [[[spellController arrangedObjects] objectAtIndex:row] valueForKey:@"name"];
		}
		[spellController setSortDescriptors:sort];
		[spellController setFilterPredicate:nil];
	}else if([aTableView isEqualTo:currentCharactersSpellsTable]){
		NSString *theClass=[memorisedSpellsClass stringValue];
		if([theClass isEqualToString:@"Sourcerer"]){
			theClass=@"Wizard";
		}
		if([[charController selectedObjects] count]==0)
			return nil;
		NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
		if([aTableColumn isEqualTo:[[aTableView tableColumns] objectAtIndex:0]]){
			return [[[[[[obj valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1",[theClass lowercaseString]]]] sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"level%@",theClass] ascending:YES],[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES],nil]] objectAtIndex:row] valueForKey:[NSString stringWithFormat:@"level%@",theClass]];
		}else{
			return [[[[[[obj valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1",[theClass lowercaseString]]]] sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"level%@",theClass] ascending:YES],[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES],nil]] objectAtIndex:row] valueForKey:@"name"];
		}
	}else if([aTableView isEqualTo:spellsOfLevelTable]){
		NSString *theClass=[memorisedSpellsClass stringValue];
		if([theClass isEqualToString:@"Sourcerer"]){
			theClass=@"Wizard";
		}
		if([[charController selectedObjects] count]==0)
			return nil;
		int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
		return [[[[[[[[charController selectedObjects] objectAtIndex:0] valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==1 AND level%@==%d",[theClass lowercaseString],theClass,level]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]] objectAtIndex:row] valueForKey:@"name"];
		
	}else if([aTableView isEqualTo:domainSpellsOfLevelTable]){
		if([[charController selectedObjects] count]==0)
			return nil;
		int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
		NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
		//NSLog(@"problem here?");
		return [[[[[[obj valueForKey:@"spells"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"domain==1 AND (domainName like[c] \"%@\" OR domainName like[c] \"%@\") AND levelDomain==%d",[obj valueForKey:@"domain1"],[obj valueForKey:@"domain2"],level]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]] objectAtIndex:row] valueForKey:@"name"];
	}else if([aTableView isEqualTo:spellsPerDayTable]){
		NSString *theClass=[memorisedSpellsClass stringValue];
		if([[charController selectedObjects] count]==0)
			return nil;
		NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
		if([aTableColumn isEqualTo:[[aTableView tableColumns] objectAtIndex:0]]){
			return [[[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass MATCHES \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]] objectAtIndex:row] valueForKey:@"level"];
		}else if([aTableColumn isEqualTo:[[aTableView tableColumns] objectAtIndex:1]]){
			return [[[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass MATCHES \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]] objectAtIndex:row] valueForKey:@"totalSpells"];
		}else{
			return [[[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass MATCHES \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]] objectAtIndex:row] valueForKey:@"spellsLeft"];
		}
	}else if([aTableView isEqualTo:memorisedSpellTable]){
		if([[charController selectedObjects] count]==0)
			return nil;
		int level=[[[memorisedSpellsTabs selectedTabViewItem] label] intValue];
		int level2=level;
		NSString *theClass=[memorisedSpellsClass stringValue];
		if([theClass isEqualToString:@"Ranger"] || [theClass isEqualToString:@"Paladin"]){
			level2--;
		}
		NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
		NSManagedObject *spellLevel=[[[[[obj valueForKey:@"spellLevel"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"charClass matches \"%@\"",theClass]]] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"level" ascending:YES]]] objectAtIndex:level2];
		NSManagedObject *memSpell=[[[[[spellLevel valueForKey:@"memorisedSpell"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"domain==0"]] sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:@"castable" ascending:NO],[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES],nil]] objectAtIndex:row];
		//set text colour.
		NSAttributedString *name;
		if([[memSpell valueForKey:@"castable"] boolValue]){
			name=[[NSAttributedString alloc] initWithString:[memSpell valueForKey:@"name"]
												 attributes:[NSDictionary dictionaryWithObject:[NSColor colorWithDeviceRed:0.0
																													 green:0.0
																													  blue:0.0
																													 alpha:1.0]
																						forKey:NSForegroundColorAttributeName]];
		}else{
			name=[[NSAttributedString alloc] initWithString:[memSpell valueForKey:@"name"]
												 attributes:[NSDictionary dictionaryWithObject:[NSColor colorWithDeviceRed:0.5
																													 green:0.5
																													  blue:0.5
																													 alpha:1.0]
																						forKey:NSForegroundColorAttributeName]];
		}
		return name;
	}else if([aTableView isEqualTo:metaMagicTable]){
		if([[charController selectedObjects] count]==0)
			return nil;
		NSManagedObject *obj=[[charController selectedObjects] objectAtIndex:0];
		NSManagedObject *feat=[[[[obj valueForKey:@"feats"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"type==2 AND active==1"]] objectAtIndex:row];
		if([aTableColumn isEqualTo:[[aTableView tableColumns] objectAtIndex:0]]){
			return [feat valueForKey:@"name"];
		/*}else{
			if([[feat valueForKey:@"spellMod"] hasSuffix:@"x"]){
				if([feat valueForKey:@"xValue"]==nil){
					return @"Choose...";
				}else{
					return [feat valueForKey:@"xValue"];
				}
			}else{
				return @"N/A";
			}*/
		}
	}
	return nil;
}
@end
